package com.nov.multidatasource.task;

import com.nov.multidatasource.config.RunBatchConfig;
import com.nov.multidatasource.entity.secondary.V6FileInfo;
import com.obs.services.ObsClient;
import com.obs.services.model.PutObjectRequest;
import com.tecrun.common.constant.ResultCode;
import com.tecrun.common.vo.RtnData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.concurrent.Callable;

/**
 * @ClassName UploadOBSTask
 * @Description TODO
 * @Author cxn
 * @CreateTime 2025/1/14 12:35
 * @Since 1.0.0
 */
@Slf4j
public class UploadOBSTask implements Callable<RtnData<V6FileInfo>> {

    private final V6FileInfo v6FileInfo;
    private final ObsClient oBSClient;
    private final RunBatchConfig runBatchConfig;

    public UploadOBSTask(V6FileInfo v6FileInfo, ObsClient oBSClient, RunBatchConfig runBatchConfig) {
        this.v6FileInfo = v6FileInfo;
        this.oBSClient = oBSClient;
        this.runBatchConfig = runBatchConfig;
    }

    @Override
    public RtnData<V6FileInfo> call() {
        try {
            String filePath = v6FileInfo.getCus6();
            if (StringUtils.isBlank(filePath)) {
                log.error("文件路径不存在, fileId:{}, filePath:{}", v6FileInfo.getFile_id(), filePath);
                return RtnData.error(ResultCode.ERROR.getCode(), "文件路径不存在", v6FileInfo);
            }
            File file = new File(filePath);
            if (!file.exists()) {
                log.error("本地文件不存在, fileId:{}, filePath:{}", v6FileInfo.getFile_id(), filePath);
                return RtnData.error(ResultCode.ERROR.getCode(), "本地文件不存在", v6FileInfo);
            }
            PutObjectRequest request = new PutObjectRequest();
            request.setBucketName(runBatchConfig.getObsBucketName());

            if (filePath.startsWith("/")) {
                filePath = filePath.substring(1);
            }
            request.setObjectKey(filePath);
            request.setFile(file);
            oBSClient.putObject(request);
            return RtnData.success(v6FileInfo);
        } catch (Exception e) {
            log.error("上传OBS异常", e);
            return RtnData.error(ResultCode.ERROR.getCode(), ResultCode.ERROR.getCode(), v6FileInfo);
        }
    }
}
